﻿namespace ContactsSync.Infrastructure.Behaviors
{
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Input;

    public class TextChangedCommandBehavior
    {
        public static readonly DependencyProperty CommandProperty = DependencyProperty.RegisterAttached(
           "Command",
           typeof(ICommand),
           typeof(TextChangedCommandBehavior),
           new PropertyMetadata(CommandChanged));

        public static void SetCommand(DependencyObject dependencyObject, ICommand command)
        {
            dependencyObject.SetValue(CommandProperty, command);
        }

        public static ICommand GetCommand(DependencyObject dependencyObject)
        {
            return (ICommand)dependencyObject.GetValue(CommandProperty);
        }

        private static void CommandChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
        {
            TextBox textBox = dependencyObject as TextBox;

            if (textBox != null)
            {
                if (e.NewValue != null)
                {
                    textBox.TextChanged += OnTextChanged;
                }
                else
                {
                    textBox.TextChanged -= OnTextChanged;
                }
            }
        }

        private static void OnTextChanged(object sender, TextChangedEventArgs args)
        {
            TextBox textBox = sender as TextBox;

            if (textBox != null)
            {
                ICommand command = GetCommand(textBox);

                command.Execute(textBox.Text);
            }
        }
    }
}
